import 'dart:convert';

import 'package:largefriends/res/lf_string_ext.dart';

import '../entity/entities/lf_user_entity.dart';
import '../entity/entities/type_config_list_entity.dart';
import '../service/manager/lf_store_helper.dart';
import '../utils/lf_logger.dart';
import 'lf_types.dart';

enum LfConfigTypeEnum {
  body('body'),
  deleteAccountReason('delete_account_reason'),
  distanceSparkIsEmpty('distance_spark_is_empty'),
  drink('drink'),
  education('education'),
  ethnicity('ethnicity'),
  eyes('eye'),
  feedback('feedback'),
  gender('gender'),
  hair('hair'),
  haveChildren('have_children'),
  hobby('hobby'),
  language('language'),
  marital('marital'),
  mood('mood'),
  occupation('occupation'),
  paymentType('payment_type'),
  personality('personality'),
  relation('relation'),
  religion('religion'),
  searchOrder('search_order'),
  smoke('smoke'),
  wantChildren('want_children'),
  pet('pet'),
  politicalBelief('political_belief'),
  distance('distance'),
  filterDistance('filter_distance'),
  matchSmoke('match_smoke'),
  relationship('relationship'),
  matchDrink('match_drink'),
  report('report'),

  ///report 不是并非来自服务器,本地写死的

  ///这项并不是从服务器获取的,我只是为了重复用多选框而已
  height('height');

  ///对应assets/json/type_$value.json
  final String value;

  const LfConfigTypeEnum(this.value);

  @override
  String toString() => 'The $name type is assets/type/lf_type_$value.json';
}

class TypeConfig {
  factory TypeConfig() => _getInstance ?? const TypeConfig._();

  const TypeConfig._();

  static TypeConfig? _getInstance;

  static final Map<String, TypeConfigListEntity> _single = {};

  Future initConfig() async {
    for (var element in LfConfigTypeEnum.values) {
      TypeConfigListEntity? entity = await _readDefaultList(element);
      if (entity != null && entity.data != null) {
        _single[element.value] = entity;
        LfStorageManager.setMap(element.name, entity.toJson()); //放到缓存中
      }
    }
  }

  /// 通过key查找值
  ///
  /// [separator]是多个值之间的分割
  String getValueByKey(LfConfigTypeEnum type, int key,
      {String defaultStr = "",
      String separator = ", ",
      bool needPlural = false,
      LfUserEntity? userEntity}) {
    StringBuffer sb = StringBuffer();
    List<TypeConfigEntity> list = getEntityLitByKey(type, key);
    for (var typeConfigEntity in list) {
      if (sb.isNotEmpty) {
        sb.write(separator);
      }
      if (type == LfConfigTypeEnum.distanceSparkIsEmpty &&
          userEntity != null &&
          userEntity.location != null &&
          (userEntity.location!.country?.isNullOrEmpty == false)) {
        //preference 的distance展示的具体一些
        if (typeConfigEntity.key == 1) {
          sb.write('In ${userEntity.location!.country}');
        } else {
          sb.write(typeConfigEntity.value);
        }
      } else if (type == LfConfigTypeEnum.gender) {
        if (typeConfigEntity.key == 1) {
          if (needPlural) {
            sb.write('Women');
          } else {
            sb.write('Woman');
          }
        }
        if (typeConfigEntity.key == 2) {
          if (needPlural) {
            sb.write('Men');
          } else {
            sb.write('Man');
          }
        }
      } else {
        sb.write(typeConfigEntity.value);
      }
    }

    String resultStr = sb.toString();
    if (resultStr.isEmpty) {
      resultStr = defaultStr;
    }
    return resultStr;
  }

  List<TypeConfigEntity> getEntityLitByKey(
    LfConfigTypeEnum type,
    int key, {
    bool needPlural = false,
  }) {
    List<TypeConfigEntity> list = [];
    TypeConfigListEntity? configListEntity = _single[type.name];

    if (configListEntity == null ||
        configListEntity.data == null ||
        configListEntity.data!.isEmpty) {
      ///获取本地sp存储
      var map = LfStorageManager.getMap(type.name);
      if (map.isNotEmpty) {
        try {
          configListEntity = TypeConfigListEntity.fromJson(map);
          _single[type.name] = configListEntity;
        } catch (e) {
          lfLogger.e(e.toString());
        }
      }
    }

    if (configListEntity != null && configListEntity.data != null) {
      if (key == 0) {
        /// key值错误,不做任何处理
        return list;
      } else {
        if (configListEntity.isBinary) {
          for (int i = 0; i < 32; i++) {
            var value = (key & (1 << i));
            if (value != 0) {
              for (var element in configListEntity.data!) {
                if (element.key == value) {
                  list.add(element);
                }
              }
            }
          }
        } else {
          for (var element in configListEntity.data!) {
            if (element.key == key) {
              list.add(element);
            }
          }
        }
      }
    }

    if (type == LfConfigTypeEnum.gender) {
      if (needPlural) {
        for (var element in list) {
          element.value = element.value
              .replaceAll(RegExp("Woman", caseSensitive: false), "Women")
              .replaceAll(RegExp("Man", caseSensitive: false), "Men");

          if (element.key == 1) {
            element.value = 'Women';
          }
          if (element.key == 2) {
            element.value = 'Men';
          }
        }
      } else {
        for (var element in list) {
          element.value = element.value
              .replaceAll(RegExp("Women", caseSensitive: false), "Woman")
              .replaceAll(RegExp("Men", caseSensitive: false), "Man");

          if (element.key == 1) {
            element.value = 'Woman';
          }
          if (element.key == 2) {
            element.value = 'Man';
          }
        }
      }
    }
    return list;
  }

  int getEntityListTotalKeys(List<TypeConfigEntity> typeEntities) {
    if (typeEntities.isEmpty) {
      return 0;
    }
    int totalKeys = 0;
    for (var element in typeEntities) {
      totalKeys += element.key;
    }
    return totalKeys;
  }

  TypeConfigListEntity getTypeConfigListEntity(LfConfigTypeEnum type) {
    TypeConfigListEntity? configListEntity = _single[type.name];
    if (configListEntity == null ||
        configListEntity.data == null ||
        configListEntity.data!.isEmpty) {
      ///获取本地sp存储
      var map = LfStorageManager.getMap(type.name);
      if (map.isNotEmpty) {
        try {
          configListEntity = TypeConfigListEntity.fromJson(map);
          _single[type.name] = configListEntity;
        } catch (e) {
          lfLogger.e(e.toString());
        }
      }
    }

    ///默认肯定拿的到
    ///_single[type.name]!拿不到 wantChildren
    ///
    return _single[type.name] ?? _single[type.value]!;
    // if (_single[type.name] != null) {
    //   return _single[type.name]!;
    // } else {
    //   return _single[type.value]!;
    // }
  }

  bool isContainKey(int key, int total) => key & total != 0;

  Future<TypeConfigListEntity?> _readDefaultList(
      LfConfigTypeEnum configType) async {
    TypeConfigListEntity? typeConfigListEntity;
    try {
      typeConfigListEntity = getConfigListEntity(configType);
    } catch (e) {
      lfLogger.e('$e--_readDefaultList-$configType');
    }

    return typeConfigListEntity;
  }

  Map<String, dynamic> parseData(String data) {
    return json.decode(data) as Map<String, dynamic>;
  }
}
